<template>
  <div class="question-header">
    <h3>题目 {{ questionIndex + 1 }}</h3>
    <div class="header-actions">
      <el-button v-if="questionIndex === 0" link type="primary" @click="$emit('add-question')">
        <el-icon><Plus /></el-icon>新增题目
      </el-button>
      <el-button link type="danger" @click="$emit('remove-question')"> 删除此题 </el-button>
    </div>
  </div>

  <el-form-item
    :error="errors.title"
    :validate-status="errors.title ? 'error' : ''"
    label="题目名称"
    prop="title"
    class="required-label"
  >
    <el-input
      :model-value="singleChoiceForms[questionIndex].title"
      :rows="2"
      placeholder="请输入题目名称"
      type="textarea"
      @update:model-value="(val) => handleUpdateForm('title', val)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.options"
    :validate-status="errors.options ? 'error' : ''"
    label="题目选项"
    class="required-label"
  >
    <div class="options-container">
      <div
        v-for="(option, index) in singleChoiceForms[questionIndex].options"
        :key="index"
        class="option-item"
      >
        <div class="option-content">
          <div class="option-label">{{ option.key }}</div>
          <el-input
            :model-value="option.value"
            :status="errors[`option${index}`] ? 'error' : ''"
            placeholder="请输入选项内容"
            @update:model-value="(val) => handleUpdateOption(questionIndex, index, 'value', val)"
          >
            <template #append>
              <el-upload
                :on-success="(res) => handleUploadSuccess(res, questionIndex, index)"
                :show-file-list="false"
                action="/api/upload"
                class="upload-demo"
              >
                <el-button type="primary">添加附件</el-button>
              </el-upload>
            </template>
          </el-input>
          <el-button
            v-if="index > 1"
            circle
            class="delete-btn"
            type="danger"
            @click="removeOption(questionIndex, index)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
        <div v-if="errors[`option${index}`]" class="error-message">
          {{ errors[`option${index}`] }}
        </div>
      </div>
      <div class="add-option">
        <el-button
          v-if="singleChoiceForms[questionIndex].options.length < 26"
          link
          type="primary"
          @click="addOption(questionIndex)"
        >
          <el-icon><Plus /></el-icon>添加选项
        </el-button>
      </div>
    </div>
  </el-form-item>

  <el-form-item
    :error="errors.answer"
    :validate-status="errors.answer ? 'error' : ''"
    label="正确答案"
    prop="answer"
    class="required-label"
  >
    <el-radio-group
      :model-value="singleChoiceForms[questionIndex].answer"
      @update:model-value="(val) => handleUpdateForm('answer', val)"
    >
      <el-radio
        v-for="option in singleChoiceForms[questionIndex].options"
        :key="option.key"
        :value="option.key"
      >
        {{ option.key }}
      </el-radio>
    </el-radio-group>
  </el-form-item>

  <el-form-item label="答案解析" prop="analysis">
    <el-input
      :model-value="singleChoiceForms[questionIndex].analysis"
      :rows="3"
      placeholder="请输入答案解析"
      type="textarea"
      @update:model-value="handleUpdateForm('analysis', $event)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.difficulty"
    :validate-status="errors.difficulty ? 'error' : ''"
    label="难度系数"
    prop="difficulty"
    class="required-label"
  >
    <el-radio-group
      :model-value="singleChoiceForms[questionIndex].difficulty"
      @update:model-value="(val) => handleUpdateForm('difficulty', val)"
    >
      <el-radio :value="1">简单</el-radio>
      <el-radio :value="2">中等</el-radio>
      <el-radio :value="3">困难</el-radio>
    </el-radio-group>
  </el-form-item>

  <!-- 添加题目分类选择器 -->
  <el-form-item label="题目分类" prop="classId">
    <class-select
      v-model="singleChoiceForms[questionIndex].classId"
      :type="2"
      placeholder="请选择题目分类(选填)"
      @change="(val) => handleUpdateForm('classId', val)"
    />
  </el-form-item>
</template>

<script lang="ts" setup>
import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useQuestionStore } from '@/store/modules/material/question'
import ClassSelect from '../../compont/ClassSelect.vue'

// 定义选项接口
interface QuestionOption {
  key: string
  value: string
  attachment?: string
}

// 定义表单接口
interface SingleChoiceForm {
  title: string
  options: QuestionOption[]
  answer: string
  analysis: string
  difficulty: number
  classId?: number
}

const props = defineProps<{
  questionIndex: number
  tabName?: string
}>()

const questionStore = useQuestionStore()
const { singleChoiceForms } = storeToRefs(questionStore)
const { updateSingleChoiceForm, updateOption, addOption, removeOption } = questionStore

const errors = ref<Record<string, string>>({})

// 添加实时校验方法
const validateField = (field: string) => {
  const form = singleChoiceForms.value?.[props.questionIndex]
  if (!form) return

  errors.value = { ...errors.value }
  delete errors.value[field]

  switch (field) {
    case 'title':
      if (!form.title?.trim()) {
        errors.value.title = '请输入题目标题'
      }
      break
    case 'options':
      if (!form.options || form.options.length < 2) {
        errors.value.options = '至少需要2个选项'
      } else {
        form.options.forEach((option, i) => {
          if (!option?.value?.trim()) {
            errors.value[`option${i}`] = `选项${option?.key || ''}的内容不能为空`
          }
        })
      }
      break
    case 'answer':
      if (!form.answer) {
        errors.value.answer = '请选择正确答案'
      }
      break
    case 'difficulty':
      if (!form.difficulty) {
        errors.value.difficulty = '请选择难度系数'
      }
      break
  }
}

// 修改更新表单的方法，添加实时校验
const handleUpdateForm = (field: keyof SingleChoiceForm, value: any) => {
  if (typeof props.questionIndex !== 'number') return
  updateSingleChoiceForm(props.questionIndex, field, value)
  validateField(field as string)
}

// 修改更新选项的方法，添加实时校验
const handleUpdateOption = (
  questionIndex: number,
  optionIndex: number,
  field: keyof Omit<QuestionOption, 'key'>,
  value: string
) => {
  if (typeof questionIndex !== 'number' || typeof optionIndex !== 'number') return
  updateOption(questionIndex, optionIndex, field, value)
  // 清除当前选项的错误
  errors.value = { ...errors.value }
  delete errors.value[`option${optionIndex}`]

  // 检查所有选项是否都已填写
  const form = singleChoiceForms.value?.[questionIndex]
  if (!form) return

  const hasEmptyOption = form.options?.some((opt) => !opt?.value?.trim())
  if (hasEmptyOption) {
    form.options?.forEach((opt, idx) => {
      if (!opt?.value?.trim()) {
        errors.value[`option${idx}`] = `选项${opt?.key || ''}的内容不能为空`
      }
    })
  } else {
    // 如果所有选项都已填写，清除选项相关的所有错误
    errors.value.options = ''
  }
}

// 校验方法
const validate = () => {
  const errorMessages: string[] = []
  errors.value = {}
  const questionNumber = props.questionIndex + 1
  const tabPrefix = `【单选题】-第${questionNumber}题：`
  const form = singleChoiceForms.value?.[props.questionIndex]

  if (!form) {
    return {
      valid: false,
      errors: ['表单数据不存在']
    }
  }

  if (!form.title?.trim()) {
    errorMessages.push(`${tabPrefix}请输入题目标题`)
    errors.value.title = '请输入题目标题'
  }

  if (!form.options || form.options.length < 2) {
    errorMessages.push(`${tabPrefix}至少需要2个选项`)
    errors.value.options = '至少需要2个选项'
  } else {
    for (let i = 0; i < form.options.length; i++) {
      const option = form.options[i]
      if (!option?.value?.trim()) {
        errorMessages.push(`${tabPrefix}选项${option?.key || ''}的内容不能为空`)
        errors.value[`option${i}`] = `选项${option?.key || ''}的内容不能为空`
      }
    }
  }

  if (!form.answer) {
    errorMessages.push(`${tabPrefix}请选择正确答案`)
    errors.value.answer = '请选择正确答案'
  }

  if (!form.difficulty) {
    errorMessages.push(`${tabPrefix}请选择难度系数`)
    errors.value.difficulty = '请选择难度系数'
  }

  return {
    valid: errorMessages.length === 0,
    errors: errorMessages
  }
}

// 获取表单数据
const getFormData = () => {
  return {
    ...singleChoiceForms.value[props.questionIndex]
  }
}

// 暴露方法给父组件
defineExpose({
  validate,
  getFormData
})

// 处理附件上传成功
const handleUploadSuccess = (response: any, questionIndex: number, index: number) => {
  if (response.code === 200) {
    updateOption(questionIndex, index, 'attachment', response.data)
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

defineEmits(['add-question', 'remove-question'])
</script>

<style lang="scss" scoped>
.options-container {
  width: 100%;
}

.option-item {
  margin-bottom: 16px;

  .option-content {
    display: flex;
    align-items: stretch;

    .option-label {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      background-color: var(--el-fill-color-light);
      color: var(--el-text-color-regular);
      font-size: 14px;
      font-weight: 500;
      border: 1px solid var(--el-border-color);
      border-right: none;
      border-radius: 4px 0 0 4px;
    }

    .el-input {
      flex: 1;

      :deep(.el-input__wrapper) {
        border-radius: 0 4px 4px 0;
      }
    }

    .delete-btn {
      margin-left: 12px;
    }
  }
}

.add-option {
  margin-top: 16px;
}

:deep(.el-input-group__append) {
  padding: 0;
  .el-upload {
    height: 100%;
    .el-button {
      border: none;
      height: 100%;
      margin: 0;
    }
  }
}

// 调整表单整体样式
:deep(.el-form-item) {
  margin-bottom: 22px;

  .el-form-item__label {
    font-weight: 500;
  }
}

:deep(.el-radio-group) {
  .el-radio {
    margin-right: 20px;
    margin-bottom: 8px;
  }
}

:deep(.el-input-number) {
  width: 160px;
}

// 调整选项表单项样式
.option-form-item {
  flex: 1;
  margin-bottom: 0 !important;

  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}

.error-message {
  color: var(--el-color-danger);
  font-size: 12px;
  margin-top: 4px;
  padding-left: 40px;
}

// 必填项标识样式
.required-label {
  :deep(.el-form-item__label) {
    &::before {
      content: '*';
      color: var(--el-color-danger);
      margin-right: 4px;
    }
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h3 {
    margin: 0;
    font-size: 16px;
    color: var(--el-text-color-primary);
  }
}
</style>
